package javaMultiThreadInAction.chapter02;

import javaMultiThreadInAction.util.Tools;

import java.util.Date;

/**
 * @author xinya
 * @version 1.0
 * @project javacore
 * @description some description
 * @date 2024/1/10 18:07:38
 */
public class VisibilityDemo {
    public static void main(String[] args) throws InterruptedException {
        TimeConsumingTask timeConsumingTask = new TimeConsumingTask();
        Thread thread = new Thread(timeConsumingTask);
        thread.start();
        Date startdate = new Date();
        Thread.sleep(10000);
        System.out.println("used time: " + (new Date().getTime() -startdate.getTime()));
        timeConsumingTask.cancel();
    }
}

class TimeConsumingTask implements Runnable {
    private boolean toCancel = false;

    @Override
    public void run() {
        while (!toCancel) {
            if (doExecute()) {
                break;
            }
        }
        if (toCancel) {
            System.out.println("task was canceled.");
        } else {
            System.out.println("task done.");
        }
    }

    private boolean doExecute() {
        boolean isDone = false;
        System.out.println("executing...");
        Tools.randomPause(50);
        return isDone;
    }

    public void cancel() {
        toCancel = true;
        System.out.println(this + " canceled");
    }
}
